$(document).ready(function() {


	//初始化按钮
	$("button").button();
	
	
	
	//设置渐入渐出时间
	var timeIn=2000;
	var timeOut=4000;
	
	//记录下拉框选中的房间号（也就是表格名）
	var tbname=$("#selectRoom").find("option:selected").text();
	//将选择的表名存储起来
	$("#selectRoom").data("tbname",tbname);
	
	showInformation("当前选择的教室为："+tbname,timeIn,timeOut);
	
	
	//获取登录部门号与最大列表号
	var curDutyID = getCurrentDutyID();	
	var　id = getCurrentID();
	
	//当选项改变时
	$("#selectRoom").change(function(){
		//将改变的选项保存到变量中
		$("#selectRoom").data("tbname",$("#selectRoom").find("option:selected").text());
		//先在前端清空所有的预约
		$("#calendar").weekCalendar("clear");
		
		//重新载入预约表,要同步
		talkWithServer("action/adminDeal.php","load",$("#selectRoom").data("tbname"),false,0,false,function(data){
				for(i=0;i<data.length;i++)
				{
					$("#calendar").weekCalendar("updateEvent",data[i]);
				}
				var str="你选择的教室为："+$("#selectRoom").data("tbname");
				showInformation(str,timeIn,timeOut);	
		});		
	});	

   var $calendar = $('#calendar');


   $calendar.weekCalendar({
       displayOddEven:true,
      timeslotsPerHour : 4,
	  timeslotHeight:30,
      firstDayOfWeek : 1,
	  scrollToHourMillis:1500,
	  use24Hour:true,
	  dateFormat:"Y-M-d",
	  timeFormat:"H:i",
      businessHours :{start: 8, end: 23, limitDisplay: true },
	  minDate:Date.today().add(-30).days(),
	  maxDate:Date.today().add(30).days(),
      daysToShow : 7,
      switchDisplay: {'当天': 1, '3天': 3, '工作日': 5, '整周': 7},
	  newEventText:"创建新日程",
	  shortMonths:['1','2','3','4','5','6','7','8','9','10','11','12'],
	  longMonths:['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
	  longDays:['星期天','星期一','星期二','星期三','星期四','星期五','星期六'],	

      title: function(daysToShow) {
			return daysToShow == 1 ? '%date%' : '%start%<---->%end%';
      },
      height : function($calendar) {
         return $(window).height() - $("h1").outerHeight() - 1;
      },
      eventRender : function(calEvent, $event) {
			//如果不是本部门的	
		if(calEvent.duty!=$("#calendar").data("dutyID"))
		{	  
			 $event.css("backgroundColor","#C1D31B");
			 $event.find(".wc-time").css({
				 	"backgroundColor":"#BED112",
					"border":"2px dashed #1232D1"
				 });
			 $event.find(".wc-title").css({
				 	"color":"#F95A36"
				 });
		}
		 //过期事件
         if (calEvent.end.getTime() < new Date().getTime()) {
            $event.css("backgroundColor", "#aaa");
            $event.find(".wc-time").css({
               "backgroundColor" : "#999",
               "border" : "1px solid #888"
            });
         }
      },
	  
	  eventAfterRender:function(calEvent,$event){
			 $calendar.weekCalendar("removeUnsavedEvents");
	  },
      draggable : function(calEvent, $event) {
		  //只有同一个部门的人才可以拖动
         return calEvent.duty == $("#calendar").data("dutyID");
      },
      resizable : function(calEvent, $event) {
         return calEvent.duty == $("#calendar").data("dutyID");
      },
      eventNew : function(calEvent, $event) {
		  		  
		 var $dialogContent = $("#event_edit_container");
         resetForm($dialogContent);
         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         var titleField = $dialogContent.find("input[name='title']");
         var bodyField = $dialogContent.find("textarea[name='body']");
         

         $dialogContent.dialog({
            modal: true,
            title: "新建预约",
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },
            buttons: {
               "保存" : function() {
                  calEvent.id = id;
                  id++;
                  calEvent.start = new Date(startField.val());
                  calEvent.end = new Date(endField.val());
                  calEvent.title = titleField.val();
                  calEvent.body = bodyField.val();
				  calEvent.duty = $("#calendar").data("dutyID");

				  //如果时间大于两个小时则不保存,getTime返回是毫秒数，两个小时是7200000		  
				  if(calEvent.end.getTime()-calEvent.start.getTime()>7200050)
				  {
					  showInformation("操作不成功<br />注意：设定时间不能大于两个小时！",timeIn,timeOut);
					  return;
				  }

                  $calendar.weekCalendar("removeUnsavedEvents");
                  $calendar.weekCalendar("updateEvent", calEvent);

				
				//插入数据
				 talkWithServer("action/adminDeal.php","insert",$("#selectRoom").data("tbname"),true,obj2str(calEvent),false,function(data){
					showInformation(data,timeIn,timeOut);											
				});
				
				 //刷新视图
				//$("#calendar").weekCalendar("refresh");	
				$dialogContent.dialog("close");			   
 
               },
               "取消" : function() {
                  $dialogContent.dialog("close");
               }
            }
         }).show();

         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));

      },
      eventDrop : function(calEvent, $event) {

		 //与服务器通话，更新数据库中的预约
		 talkWithServer("action/adminDeal.php","update",$("#selectRoom").data("tbname"),true,obj2str(calEvent),true,function(data){
				showInformation(data,timeIn,timeOut);
		 });
     		 //刷新视图
			$("#calendar").weekCalendar("refresh");		  
      },
      eventResize : function(calEvent, $event) {
		  
		　//如果时间大于两个小时则不保存,getTime返回是毫秒数，两个小时是7200000		  
		  if(calEvent.end.getTime()-calEvent.start.getTime()>7200050)
		  {
			  showInformation("拖曳操作不成功！<br />注意：设定时间不能大于两个小时！",timeIn,timeOut);		 
			  
		  }
		  else
		  {
			  //console.log(calEvent.start);
			  //console.log(calEvent.end);
			 //与服务器通话，更新数据库中的预约
			 	var tempEvent = calEvent;
				tempEvent.start = tempEvent.start.toString('s');
				tempEvent.end = tempEvent.end.toString('s');
			 
			 talkWithServer("action/adminDeal.php","update",$("#selectRoom").data("tbname"),$("#calendar").data("dutyID"),JSON.stringify(tempEvent),true,function(data){
					showInformation(data,timeIn,timeOut);
			 });
		  }
		  
		  //重新刷新视图
		   $("#calendar").weekCalendar("refresh");		  
      },
      eventClick : function(calEvent, $event) {
		 
		if(calEvent.duty != $("#calendar").data("dutyID"))
		{
			return;
		}
         var $dialogContent = $("#event_edit_container");
         resetForm($dialogContent);
         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         var titleField = $dialogContent.find("input[name='title']").val(calEvent.title);
         var bodyField = $dialogContent.find("textarea[name='body']");
         bodyField.val(calEvent.body);

         $dialogContent.dialog({
            modal: true,
            title: "编辑 - " + calEvent.title,
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },
            buttons: {
               "保存" : function() {

                  calEvent.start = new Date(startField.val());
                  calEvent.end = new Date(endField.val());
                  calEvent.title = titleField.val();
                  calEvent.body = bodyField.val();
				  calEvent.duty = $("#calendar").data("dutyID");
				  
				  console.log(calEvent.end.getTime()-calEvent.start.getTime());
				  //如果时间大于两个小时则不保存,getTime返回是毫秒数，两个小时是7200000		  
				  if(calEvent.end.getTime()-calEvent.start.getTime()>7200050)
				  {
					  showInformation("操作不成功！<br />注意：设定时间不能大于两个小时！",timeIn,timeOut);
					  return;
				  }
				  

                  $calendar.weekCalendar("updateEvent", calEvent);
                  $dialogContent.dialog("close");
				 　//console.dir(calEvent);
				 
				 //与服务器通话，更新数据库中的预约
				 talkWithServer("action/adminDeal.php","update",$("#selectRoom").data("tbname"),true,obj2str(calEvent),true,function(data){
					 	showInformation(data,timeIn,timeOut);
				});	
				//刷新视图
				$("#calendar").weekCalendar("refresh");							  
               },
               "删除" : function() {
                  $calendar.weekCalendar("removeEvent", calEvent.id);
                  $dialogContent.dialog("close");

				//与服务器通话，保持数据同步
				 talkWithServer("action/adminDeal.php","delete",$("#selectRoom").data("tbname"),true,obj2str(calEvent),true,function(data){
					 	showInformation(data,timeIn,timeOut);
				 });			  
               },
               "取消" : function() {
                  $dialogContent.dialog("close");
               }
            }
         }).show();

         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
         $(window).resize().resize(); //fixes a bug in modal overlay size ??

      },
      eventMouseover : function(calEvent, $event) {
      },
      eventMouseout : function(calEvent, $event) {
      },
      noEvents : function() {

      },

      reachedmindate: function($calendar, date){
        showInformation("不能查看一个月以前的记录！",timeIn,timeOut);
      },
      reachedmaxdate: function($calendar, date){
        showInformation("不能预约一个月以后的日期！",timeIn,timeOut);
      },
	  
      data : function(start, end, callback) {
         callback(getEventData());
      }
   });


   function getEventData() {
	   
		//与服务器通话，由于要等数据到达，所以需要同步，让async为false
		 talkWithServer("action/adminDeal.php","load",$("#selectRoom").data("tbname"),false,0,false,function(data){
				var dataArr=new Array();
				
				for(i=0;i<data.length;i++)
				{
					dataArr[i]=data[i];
				}
				//将数据存储到某个选择器上
				$("#calendar").data("initData",{events:dataArr});
		 });
		 
		 return $("#calendar").data("initData");
   }


   /*
    * Sets up the start and end time fields in the calendar event
    * form for editing based on the calendar event being edited
    */
   function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {

      $startTimeField.empty();
      $endTimeField.empty();

      for (var i = 0; i < timeslotTimes.length; i++) {
         var startTime = timeslotTimes[i].start;
         var endTime = timeslotTimes[i].end;
         var startSelected = "";
         if (startTime.getTime() === calEvent.start.getTime()) {
            startSelected = "selected=\"selected\"";
         }
         var endSelected = "";
         if (endTime.getTime() === calEvent.end.getTime()) {
            endSelected = "selected=\"selected\"";
         }
         $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
         $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

         $timestampsOfOptions.start[timeslotTimes[i].startFormatted] = startTime.getTime();
         $timestampsOfOptions.end[timeslotTimes[i].endFormatted] = endTime.getTime();

      }
      $endTimeOptions = $endTimeField.find("option");
      $startTimeField.trigger("change");
   }

   var $endTimeField = $("select[name='end']");
   var $endTimeOptions = $endTimeField.find("option");
   var $timestampsOfOptions = {start:[],end:[]};

   //reduces the end time options to be only after the start time options.
   $("select[name='start']").change(function() {
      var startTime = $timestampsOfOptions.start[$(this).find(":selected").text()];
      var currentEndTime = $endTimeField.find("option:selected").val();
      $endTimeField.html(
            $endTimeOptions.filter(function() {
               return startTime < $timestampsOfOptions.end[$(this).text()];
            })
            );

      var endTimeSelected = false;
      $endTimeField.find("option").each(function() {
         if ($(this).val() === currentEndTime) {
            $(this).attr("selected", "selected");
            endTimeSelected = true;
            return false;
         }
      });

      if (!endTimeSelected) {
         //automatically select an end date 2 slots away.
         $endTimeField.find("option:eq(1)").attr("selected", "selected");
      }

   });



    //显示当前房间全部的预约列表
	$("#allbook_button").click(function(){
		
		var allBook=$("#calendar").weekCalendar("serializeEvents");
		html="";
		for(i=0;i<allBook.length;i++)
		{
			html+=allBook[i].title+"<br/>";
		}
		showInformation(html,timeIn,timeOut);	
	});


	//显示最大ID号
	$('#maxID_button').click(function(){
		var maxid = getCurrentID();
		showInformation(maxid,timeIn,timeOut);			
	});
	
	
	//显示当前登录的部门号
	$("#dutyID_button").click(function(){
		var dutyID = getCurrentDutyID();
		showInformation(dutyID,timeIn,timeOut);	
	});
	


	$("#clear_button").click(function(){
		
		var info=" 　　　确定要清空教室“"+$("#selectRoom").data("tbname")+"”所有预约？\n此操作不可逆，请慎重！";
		if(confirm(info))
		{
			
			//与服务器通话，保持数据同步
			 talkWithServer("action/adminDeal.php","deleteall",$("#selectRoom").data("tbname"),false,0,false,function(data){
					showInformation(data,timeIn,timeOut);
			 });
			 
			 //在前端清空所有的预约
			$("#calendar").weekCalendar("clear");
			id=1;
		}
		else
		{
			showInformation("你已经取消了删除操作",timeIn,timeOut);			
		}
			
	});
	
	$("#delete_button").click(function(){
		
		var info=" 　　　确定要删除教室“"+$("#selectRoom").data("tbname")+"”？\n此操作不可逆，请慎重！";
		if(confirm(info))
		{
			
			//与服务器通话，保持数据同步
			 talkWithServer("action/adminDeal.php","dropTable",$("#selectRoom").data("tbname"),false,0,false,function(data){
					showInformation(data,timeIn,timeOut);
			 });
		//重新进入页面
		window.location ="../../roomadmin.php";	
		}
		else
		{
			showInformation("你已经取消了删除操作",timeIn,timeOut);			
		}
			
	});	

   var $about = $("#about");

   $("#about_button").click(function() {
      $about.dialog({
         title: "About this calendar demo",
         width: 600,
         close: function() {
            $about.dialog("destroy");
            $about.hide();
         },
         buttons: {
            close : function() {
               $about.dialog("close");
            }
         }
      }).show();
   });


   //注销按钮
   $("#logout_button").click(function(){

		talkWithServer('action/login.php','logout','user',false,0,false,function(data){
			    
				if(data=="success")
					//成功注销，使用js进制重定向
					window.location ="roombooking.php";	
				else
					showInformation(data,timeIn,timeOut);
		});			   
		   
   });


	//增加教室
	$("#addRoom").click(function(){
		//用ID选择器不行，最好使用input:text选择
		var roomNum=$("input:text").val();
		
		//
		var reg=/^[1-9]{1,2}-[0-9]*$/;
		if(reg.test(roomNum))
		{		  				
			//不重复添加下拉框选项
			for(var j=0;j<$("#selectRoom option").length;j++)
			{
				if($("#selectRoom option:eq("+j+")").val()==roomNum)
				{
					alert("此项已经存在，不能添加");
					return;
				}
			}
			$("<option value='"+roomNum+"'>"+roomNum+"</option>").appendTo("#selectRoom")//添加下拉框的option
			//同时在数据库里创建新表
			talkWithServer("action/adminDeal.php","createTable",roomNum,false,0,false,function(data){
				showInformation("成功创建教室“"+roomNum+"”的预定表！<br />"+data,timeIn,timeOut);		
			});
		}
		else
		{
			alert("输入格式不正确，请看“关于”内容");
		}
		//马上清空输入框
		$("input:text").val("");		
	});


	
	
	//清空输入框
   function resetForm($dialogContent) {
      $dialogContent.find("input").val("");
      $dialogContent.find("textarea").val("");
   }


   /*
    * Sets up the start and end time fields in the calendar event
    * form for editing based on the calendar event being edited
    */
   function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {

      $startTimeField.empty();
      $endTimeField.empty();

      for (var i = 0; i < timeslotTimes.length; i++) {
         var startTime = timeslotTimes[i].start;
         var endTime = timeslotTimes[i].end;
         var startSelected = "";
         if (startTime.getTime() === calEvent.start.getTime()) {
            startSelected = "selected=\"selected\"";
         }
         var endSelected = "";
         if (endTime.getTime() === calEvent.end.getTime()) {
            endSelected = "selected=\"selected\"";
         }
         $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
         $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

         $timestampsOfOptions.start[timeslotTimes[i].startFormatted] = startTime.getTime();
         $timestampsOfOptions.end[timeslotTimes[i].endFormatted] = endTime.getTime();

      }
      $endTimeOptions = $endTimeField.find("option");
      $startTimeField.trigger("change");
   }

   var $endTimeField = $("select[name='end']");
   var $endTimeOptions = $endTimeField.find("option");
   var $timestampsOfOptions = {start:[],end:[]};

   //reduces the end time options to be only after the start time options.
   $("select[name='start']").change(function() {
      var startTime = $timestampsOfOptions.start[$(this).find(":selected").text()];
      var currentEndTime = $endTimeField.find("option:selected").val();
      $endTimeField.html(
            $endTimeOptions.filter(function() {
               return startTime < $timestampsOfOptions.end[$(this).text()];
            })
            );

      var endTimeSelected = false;
      $endTimeField.find("option").each(function() {
         if ($(this).val() === currentEndTime) {
            $(this).attr("selected", "selected");
            endTimeSelected = true;
            return false;
         }
      });

      if (!endTimeSelected) {
         //automatically select an end date 2 slots away.
         $endTimeField.find("option:eq(1)").attr("selected", "selected");
      }

   });

	//获取当前房间的最大的ID号
	function getCurrentID()
	{
		//与服务器通话，获取当前最大ID号，注意不能使用异步，否则保存的数据会不存在——因为先执行了success函数
		 talkWithServer("action/adminDeal.php","maxID",$("#selectRoom").data("tbname"),false,0,false,function(data){
				$("#calendar").data("maxID",data);
		});	
		//获取存储的最大ID号
		var maxid=$("#calendar").data("maxID");
		//转换成数字
		maxid=Number(maxid)+1;
		return maxid;		
		
	}
	
	
	//获取当前登录部门的ID号
	function getCurrentDutyID()
	{
		//与服务器通话，获取当前登录部门的ID号，注意不能使用异步，否则保存的数据会不存在——因为先执行了success函数
		 talkWithServer("action/adminDeal.php","dutyID",$("#selectRoom").data("tbname"),false,0,false,function(data){
				$("#calendar").data("dutyID",data);
		});
		//返回当前登录部门的ID号
		return	Number($("#calendar").data("dutyID"));
	}


	//与服务器通话
	function talkWithServer(page,action,tbname,hasEvent,queryStr,isasync,func)
	{
		 jsondata='action='+action+"&hasEvent="+hasEvent+"&"+queryStr+"&tbname="+tbname;
		 
		 $.ajax({
			 type:"POST",
			 url:page,
			 async:isasync,
			 data:jsondata,
			 success:function(data)
			 {
				 func(data);
			 }
			 
		});	
	}

	//事件对象转换成查询字符串,涉及时间格式的转换
	function obj2str(calEvent)
	{
　		//console.log(calEvent.start.toString('s'));
		var tempEvent = calEvent;
		tempEvent.start = tempEvent.start.toString('s');
		tempEvent.end = tempEvent.end.toString('s');
		var tempString="id="+tempEvent.id+"&"+
				   "start="+tempEvent.start+"&"+
				   "end="+tempEvent.end+"&"+
				   "title="+tempEvent.title+"&"+
				   "body="+tempEvent.body;
		return tempString;
		
	}


	//显示提示
	function showInformation(msg,timeIn,timeOut)
	{
		$("#show").html(msg).fadeIn(timeIn);
	}

});
